<?php
/**
 * file task 数据操作层
 * Created by <xinxin.deng>.
 * Author: xinxin.deng
 * Date: 2018/11/13 11:56
 */
include_once dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'public.class.php';
class nl_file_task extends nl_public
{
    static $base_table='nns_mgtvbk_file_task';
    static $arr_filed = array(
        'nns_id',
        'nns_type',
        'nns_name',
        'nns_ref_id',
        'nns_action',
        'nns_status',
        'nns_create_time',
        'nns_modify_time',
        'nns_org_id',
        'nns_category_id',
        'nns_src_id',
        'nns_all_index',
        'nns_clip_task_id',
        'nns_clip_date',
        'nns_op_id',
        'nns_epg_status',
        'nns_ex_url',
        'nns_file_path',
        'nns_file_size',
        'nns_file_md5',
        'nns_cdn_policy',
        'nns_epg_fail_time',
        'nns_message_id',
        'nns_is_group',
        'nns_weight',
        'nns_cp_id',
        'nns_cdn_fail_time',
        'nns_notify_third_state',
        'nns_queue_execute_url',
        'nns_cdn_import_id',//cdn注入id xinxin.deng 2018/3/2 14:52
    );


    /**
     * 查询file队列注入的元数据的状态
     * @param $dc
     * @param $mix_id
     * @param $sp_id
     * @param $type
     * @return array
     */
    static public function query_end_state($dc,$mix_id,$sp_id,$type)
    {
        $str_sql = is_string($mix_id) ? $mix_id : implode("','", $mix_id);
        if(empty($str_sql))
        {
            return self::return_data(1,'id为空');
        }
        switch ($type)
        {
            case 'video':
                $sql="select nns_ref_id,nns_src_id from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and " .
                    " nns_ref_id in ('{$str_sql}') and nns_epg_status='99' and nns_action in('add','modify') ";
                break;
            case 'index':
                $sql="select nns_ref_id,nns_src_id from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and " .
                    " nns_src_id in ('{$str_sql}') and nns_epg_status='99' and nns_action in('add','modify') ";
                break;
            case 'media':
                $sql="select nns_ref_id,nns_src_id from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and " .
                    " nns_src_id in ('{$str_sql}') and nns_epg_status='99' and nns_action in('add','modify') ";
                break;
            default:
                return self::return_data(1,'没有此类型');
        }
        $result = nl_query_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库执行失败'.$sql);
        }
        return self::return_data(0,'ok',$result);
    }


    static public function query_c2_exsist($dc,$type,$mix_id,$sp_id)
    {
        $str_sql = is_string($mix_id) ? $mix_id : implode("','", $mix_id);
        if(empty($str_sql))
        {
            return self::return_data(1,'id为空');
        }
        switch ($type)
        {
            case 'video':
                $sql="select * from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and nns_ref_id in ('{$str_sql}')";
                break;
            case 'index':
                $sql="select * from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and nns_ref_id in ('{$str_sql}')";
                break;
            case 'media':
                $sql="select * from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and nns_ref_id in ('{$str_sql}')";
                break;
            case 'live':
                $sql="select * from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and nns_ref_id in ('{$str_sql}')";
                break;
            case 'live_index':
                $sql="select * from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and nns_ref_id in ('{$str_sql}')";
                break;
            case 'live_media':
                $sql="select * from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and nns_ref_id in ('{$str_sql}')";
                break;
            case 'playbill':
                $sql="select * from " . self::$base_table . " where nns_type='{$type}' and nns_org_id='{$sp_id}' and nns_ref_id in ('{$str_sql}')";
                break;
            default:
                return self::return_data(1,'没有此类型');
        }
        $result = nl_query_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库执行失败'.$sql);
        }
        return self::return_data(0,'ok',$result);
    }

    /**
     * 添加file task 队列
     * @param $dc
     * @param $params
     * @return array
     */
    static public function add($dc,$params)
    {
        $params = self::make_nns_pre($params);
        if(!isset($params['nns_id']) || strlen($params['nns_id'])<1)
        {
            $params['nns_id'] = np_guid_rand();
        }
        $date_time = date("Y-m-d H:i:s");
        if(!isset($params['nns_create_time']) || strlen($params['nns_create_time'])<1)
        {
            $params['nns_create_time'] = $date_time;
        }
        if(!isset($params['nns_modify_time']) || strlen($params['nns_modify_time'])<1)
        {
            $params['nns_modify_time'] = $date_time;
        }
        $params = self::except_useless_params(self::$arr_filed, $params);
        if(empty($params))
        {
            return self::return_data(1,'参数为空');
        }
        $sql = self::make_insert_sql(self::$base_table, $params);
        $result = nl_execute_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库执行失败'.$sql);
        }
        return self::return_data(0,'ok');
    }

    /**
     * 修改file task队列
     * @param $dc
     * @param $params
     * @param $nns_id
     * @return array
     */
    static public function edit($dc,$params,$nns_id)
    {
        $params = self::make_nns_pre($params);
        if((is_string($nns_id) && strlen($nns_id) <1) || (is_array($nns_id) && !empty($nns_id)))
        {
            return self::return_data(1,'CDN直播频道队列guid为空');
        }
        $params = self::except_useless_params(self::$arr_filed, $params);
        if(empty($params))
        {
            return self::return_data(1,'参数为空');
        }
        if(!isset($params['nns_modify_time']) || strlen($params['nns_modify_time'])<1)
        {
            $params['nns_modify_time'] = date("Y-m-d H:i:s");
        }
        $sql = self::make_update_sql(self::$base_table, $params,array('nns_id'=>$nns_id));
        $result = nl_execute_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库执行失败'.$sql);
        }
        return self::return_data(0,'ok:'.$sql);
    }

    /**
     * 依据条件查询file task信息
     * @param $dc
     * @param $params
     * @return array
     */
    static public function query_by_condition_v2($dc, $params)
    {
        $params = self::except_useless_params(self::$arr_filed, $params);
        if (!is_array($params) || empty($params))
        {
            return self::return_data(1, '查询条件为空不允许查询');
        }
        $sql = self::make_query_sql(self::$base_table, $params);
        $result = nl_query_by_db($sql, $dc->db());
        if (!$result)
        {
            return self::return_data(1, '数据库查询失败,sql:' . $sql);
        }
        $result = (isset($result) && !empty($result)) ? $result : null;
        return self::return_data(0, 'OK' . $sql, $result);
    }

    /**
     * 根据id查询file task 的任务信息 -- 批量查询
     * @param $dc
     * @param $nns_id
     * @return array
     */
    static public function query_data_by_id($dc,$nns_id)
    {
        $nns_id = is_array($nns_id) ? $nns_id : array($nns_id);
        if(empty($nns_id))
        {
            return self::return_data(1,"参数ID 为空");
        }
        $nns_id = array_values($nns_id);
        $sql="select * from " . self::$base_table . " where nns_id in('".implode("','", $nns_id)."')";
        $result = nl_query_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库执行失败'.$sql);
        }
        return self::return_data(0,'ok:'.$sql,$result);
    }

    /**
     * 根据id查询file task 的任务信息 -- 单个查询
     * @param $dc
     * @param $nns_id
     * @return array
     */
    static public function query_by_id($dc,$nns_id)
    {
        $sql = "select * from " . self::$base_table . " where nns_id='{$nns_id}' limit 1";
        $result = nl_query_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库查询失败,sql:'.$sql);
        }
        $result = (isset($result[0]) && !empty($result[0])) ? $result[0] : null;
        return self::return_data(0,'OK:'.$sql,$result);
    }

    /**
     * 取消file task 任务
     * @param $dc
     * @param $params
     * @param $where
     * @return array
     */
    static public function cancel_c2_task($dc, $params,$where)
    {
        if(!is_array($params) || empty($params) || !is_array($where) || empty($where))
        {
            return self::return_data(1,'参数错误');
        }
        $set_str = '';
        foreach ($params as $k=>$val)
        {
            $set_str .= "{$k} = '{$val}',";
        }
        $set_str = rtrim($set_str,",");

        $where_str = '';
        foreach ($where as $key=>$value)
        {
            if($key === 'in' && !empty($value) && is_array($value))
            {
                foreach ($value as $key_in => $in_value)
                {
                    if(is_array($in_value) && !empty($in_value))
                    {
                        $in_ids = implode("','", $in_value);
                        $where_str .= " {$key_in} in ('{$in_ids}') AND ";
                    }
                }
            }
            elseif(!empty($value) || $value == '0')
            {
                $where_str .= " {$key} = '{$value}' AND ";
            }
        }
        $where_str = rtrim($where_str," AND ");
        if(!empty($where_str))
        {
            $where_str = " WHERE " . $where_str;
        }
        $sql = "UPDATE " . self::$base_table . " SET {$set_str} {$where_str}";
        $result = nl_execute_by_db($sql, $dc->db());
        if($result === false)
        {
            return self::return_data(1,'mysql execute failed');
        }
        else
        {
            return self::return_data(0,'OK');
        }
    }

    /**
     * 通过消息id进行查询
     * @param $dc
     * @param $message_id
     * @param $sp_id
     * @param $video_type
     * @return array
     */
    static public function query_message_by_message_id($dc,$message_id,$sp_id,$video_type)
    {
        $str_temp = (is_array($sp_id) && !empty($sp_id)) ? " and nns_org_id in ('" . implode("','", $sp_id) . "') " : " and nns_org_id = '{$sp_id}' ";
        $sql="select * from " . self::$base_table . " where nns_message_id='{$message_id}' and nns_type='{$video_type}' {$str_temp} limit 1" ;
        $result = nl_query_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'消息队列查询失败'.$sql);
        }
        $result = (isset($result[0]) && !empty($result[0]) && is_array($result[0])) ? $result[0] : null;
        return self::return_data(0,'ok',$result);
    }


    /**
     * 编辑发送cdn的失败次数，并且修改返送cdn的状态
     * @param $dc
     * @param $nns_id
     * @return array
     */
    static public function edit_cdn_fail_time($dc,$nns_id)
    {
        $date = date("Y-m-d H:i:s");
        if(!(is_string($nns_id) && strlen($nns_id) <1) || !(is_array($nns_id) && !empty($nns_id)))
        {
            return self::return_data(1,'EPGFile 注入CDN队列guid为空');
        }
        $str_id = (is_array($nns_id)) ? implode("','", $nns_id) : $nns_id;
        $sql="update " . self::$base_table . " set nns_cdn_fail_time=nns_cdn_fail_time+1,nns_modify_time='{$date}',nns_state=-1 where nns_id in('{$str_id}')";
        $result = nl_execute_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库执行失败'.$sql);
        }
        return self::return_data(0,'ok '.$sql);
    }

    /**
     * 编辑发送cdn的失败次数
     * @param $dc
     * @param $nns_id
     * @return array
     */
    static public function edit_cdn_fail_time_v2($dc,$nns_id)
    {
        $date = date("Y-m-d H:i:s");
        if(!(is_string($nns_id) && strlen($nns_id) <1) || !(is_array($nns_id) && !empty($nns_id)))
        {
            return self::return_data(1,'EPGFile 注入CDN队列guid为空');
        }
        $str_id = (is_array($nns_id)) ? implode("','", $nns_id) : $nns_id;
        $sql="update " . self::$base_table . " set nns_cdn_fail_time=nns_cdn_fail_time+1,nns_modify_time='{$date}' where nns_id in('{$str_id}')";
        $result = nl_execute_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库执行失败'.$sql);
        }
        return self::return_data(0,'ok '.$sql);
    }

    /**
     * 根据条件获取
     * @param object $dc
     * @param array $params
     * @return array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
     */
    static public function query_by_condition($dc,$params,$since = '',$num = '',$str_order='')
    {
        if (empty($params) || !is_array($params))
        {
            return self::return_data(1,'参数错误');
        }
        $where = '';
        foreach ($params as $key=>$val)
        {
            $where .= "$key='{$val}' and ";
        }
        $where = rtrim($where," and ");
        if(!empty($where))
        {
            $where = " where " . $where;
        }

        if(!empty($str_order) && strlen($str_order) >0)
        {
            $where .= " {$str_order} ";
        }

        if (strlen($since) > 0 && strlen($num) > 0)
        {
            $limit = ' limit ' . $since . ',' . $num;
        }
        else
        {
            $limit = '';
        }
        $sql = "select * from " . self::$base_table . $where . $limit;
        $result = nl_query_by_db($sql, $dc->db());
        if(!is_array($result))
        {
            return self::return_data(1,'没有数据'.$sql);
        }
        return self::return_data(0,'ok',$result);
    }

    /**
     * 删除日志  通过 状态和日期，目前只支持删除节目单
     * @param $dc
     * @param $sp_id
     * @param $str_date
     * @param bool $flag_cdn
     * @param bool $epg_state
     * @return array
     */
    static public function del_by_date_and_state($dc,$sp_id,$str_date,$flag_cdn =true ,$epg_state=true)
    {
        if(strlen($sp_id) <1)
        {
            return self::return_data(1,'删除的$sp_id为空');
        }
        if(strlen($str_date) <1)
        {
            return self::return_data(1,'删除的创建日期为空');
        }
        if(!$flag_cdn && !$epg_state)
        {
            return self::return_data(1,'CDN['.var_export($flag_cdn,true).']、EPG['.var_export($epg_state,true).']状态必须要有一个为终态');
        }
        $sql = "delete from " . self::$base_table . " where nns_org_id='{$sp_id}' and nns_type='playbill' ";
        if($flag_cdn)
        {
            $sql .= " and nns_status='0' ";
        }
        if($flag_cdn)
        {
            $sql .= " and nns_epg_status='99' ";
        }
        $sql.=" and nns_create_time <='{$str_date}' ";
        $result = nl_execute_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库执行失败'.$sql);
        }
        return self::return_data(0,'ok '.$sql);
    }
    /**
     * 定时器：业务逻辑层SQL---按条件获取注入CDN的任务
     * @param object $dc DC
     * @param $params array(
     *                    'key'=>'value',
     *                    'less_than' => array(
     *                              'key' => 'value',
     *                     ),
     *                     'more_than' => array(
     *                              'key' => 'value',
     *                     ),
     *                     'in' => array(
     *                              'key' => array('value1','value2'),
     *                     ),
     *                     'not_in' => array(
     *                              'key' => array('value1','value2'),
     *                     ),
     *                )
     * @param int $limit 条数
     * @param $str_group group by
     * @param $str_order order by
     * @return array
     */
    static public function timer_get_c2_task($dc,$params,$limit=1,$str_group='',$str_order='')
    {
        $arr_where = self::__build_where($params);
        if($arr_where['ret'] != '0')
        {
            $where = '';
        }
        else
        {
            $where = $arr_where['data_info'];
        }

        if(!empty($str_group) && strlen($str_group) > 0)
        {
            $where .= " {$str_group} ";
        }

        if(!empty($str_order) && strlen($str_order) > 0)
        {
            $where .= " {$str_order} ";
        }

        if (strlen($limit) > 0)
        {
            $limit = ' limit ' . $limit;
        }
        else
        {
            $limit = '';
        }
        $sql = "select * from " . self::$base_table . $where . $limit;
        $result = nl_query_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库执行失败：'.$sql);
        }
        return self::return_data(0,'ok',$result);
    }

    /**
     * 创建where条件
     * @param $params
     * @return array array(
     *                    'key'=>'value',
     *                    'less_than' => array(
     *                              'key' => 'value',
     *                     ),
     *                     'more_than' => array(
     *                              'key' => 'value',
     *                     ),
     *                     'in' => array(
     *                              'key' => array('value1','value2'),
     *                     ),
     *                     'not_in' => array(
     *                              'key' => array('value1','value2'),
     *                     ),
     *                )
     * @return array
     */
    static public function __build_where($params)
    {
        $where = '';
        if (empty($params) || !is_array($params))
        {
            return self::return_data(1,'没有where请求参数');
        }
        foreach ($params as $key=>$val)
        {
            switch ($key)
            {
                case 'less_than':
                    if(is_array($val))
                    {
                        foreach ($val as $k=>$v)
                        {
                            $where .= "{$k}<='{$v}' and ";
                        }
                    }
                    break;
                case 'more_than':
                    if(is_array($val))
                    {
                        foreach ($val as $k=>$v)
                        {
                            $where .= "{$k}<='{$v}' and ";
                        }
                    }
                    break;
                case 'in':
                    if(is_array($val))
                    {
                        foreach ($val as $k=>$v)
                        {
                            $where .= "{$k} in ('" . implode("','",$v) . "') and ";
                        }
                    }
                    break;
                case 'not_in':
                    if(is_array($val))
                    {
                        foreach ($val as $k=>$v)
                        {
                            $where .= "{$k} not in ('" . implode("','",$v) . "') and ";
                        }
                    }
                    break;
                default:
                    $where .= "{$key}='{$val}' and ";
                    break;
            }

        }
        $where = rtrim($where," and ");
        if(empty($where))
        {
            return self::return_data(1,'没有where请求参数');
        }
        return self::return_data(0,''," where " . $where);
    }

    /**
     * 依据条件查询主媒资信息
     * @param $dc
     * @param $sql
     * @return array
     */
    static public function query_by_sql($dc, $sql)
    {
        $result = nl_query_by_db($sql, $dc->db());
        if (!$result)
        {
            return self::return_data(1, '数据库查询失败,sql:' . $sql);
        }
        $result = (isset($result) && !empty($result)) ? $result : null;
        return self::return_data(0, 'OK' . $sql, $result);
    }

    /**
     * 根据条件获取任务数据
     * @param $dc
     * @param $sp_id
     * @param null $filter
     * @param int $start
     * @param int $size
     * @return array
     */
    static public function get_file_task_list($dc, $sp_id,$filter=null,$start=0,$size=100){
        set_time_limit(0);
        $str_left_join = '';

        $sql = "select task.* from " . self::$base_table . " as task {$str_left_join} where task.nns_org_id='$sp_id'";
        if($filter != null){
            $wh_arr = array();
            if(!empty($filter['nns_name'])){
                if(strpos($filter['nns_name'], "|#|,") !== false)
                {
                    $arr = explode("|#|,", $filter['nns_name']);
                    $str_temp='';
                    foreach ($arr as $arr_temp )
                    {
                        $str_temp.= " task.nns_name like '%".$arr_temp."%' or";
                    }
                    $str_temp = rtrim(trim($str_temp),'or');
                    $wh_arr[] = " ({$str_temp}) ";
                }
                else {
                    $wh_arr[] = " task.nns_name like '%".$filter['nns_name']."%'";
                }
            }
            if(!empty($filter['day_picker_start'])){
                $wh_arr[] = " task.nns_create_time>='".$filter['day_picker_start']."'";
            }
            if(!empty($filter['day_picker_end'])){
                $wh_arr[] = " task.nns_create_time<='".$filter['day_picker_end']."'";
            }
            if(!empty($filter['nns_type'])){
                $wh_arr[] = " task.nns_type='".$filter['nns_type']."'";
            }
            if(!empty($filter['nns_action'])){
                $wh_arr[] = " task.nns_action='".$filter['nns_action']."'";
            }
            if(strlen($filter['nns_cdn_fail_time'])){
                $wh_arr[] = " task.nns_cdn_fail_time='".$filter['nns_cdn_fail_time']."'";
            }
            if(strlen($filter['nns_ref_id'])){
                $wh_arr[] = " task.nns_ref_id='".$filter['nns_ref_id']."'";
            }
            if(strlen($filter['nns_src_id'])){
                $wh_arr[] = " task.nns_src_id='".$filter['nns_src_id']."'";
            }
            if(!empty($filter['nns_state'])){
                $state = $filter['nns_state'];
                switch($state){
                    case 'content_wait':
                        $wh_arr[] = " task.nns_status=1";
                        break;
                    case 'content_ok':
                        $wh_arr[] = " task.nns_status=0";
                        break;
                    case 'content_fail':
                        $wh_arr[] = " task.nns_status=-1";
                        break;
                    case 'content_doing':
                        $wh_arr[] = " task.nns_status=5";
                        break;
                    case 'content_wait_cdi':
                        $wh_arr[] = " task.nns_status=6";
                        break;
                    case 'content_cancel':
                        $wh_arr[] = " task.nns_status=7";
                        break;
                    case 'content_wait_cdi_doing':
                        $wh_arr[] = " task.nns_status=8";
                        break;
                    case 'content_wait_cdi_fail':
                        $wh_arr[] = " task.nns_status=9";
                        break;
                    case 'ftp_connet_fail':
                        $wh_arr[] = " task.nns_status=10";
                        break;
                    case 'ftp_clip_get_fail':
                        $wh_arr[] = " task.nns_status=11";
                        break;
                    case 'content_wait_del':
                        $wh_arr[] = " task.nns_status=12";
                        break;
                    case 'content_doing_del':
                        $wh_arr[] = " task.nns_status=13";
                        break;
                    case 'content_fail_del':
                        $wh_arr[] = " task.nns_status=14";
                        break;
                }
            }

            if(!empty($filter['nns_epg_state'])){
                $epg_state = $filter['nns_epg_state'];
                switch($epg_state){
                    case 'content_epg_wait':
                        $wh_arr[] = " task.nns_epg_status=97";
                        break;
                    case 'content_epg_ok':
                        $wh_arr[] = " task.nns_epg_status=99";
                        break;
                    case 'content_epg_doing':
                        $wh_arr[] = " task.nns_epg_status=98";
                        break;
                    case 'content_epg_cancel':
                        $wh_arr[] = " task.nns_epg_status=100";
                        break;
                    case 'content_epg_fail':
                        $wh_arr[] = " task.nns_epg_status=96";
                        break;
                }
            }
            if(isset($filter['nns_cp_id']) && strlen($filter['nns_cp_id']) >0){
                $wh_arr[] = " task.nns_cp_id='{$filter['nns_cp_id']}'";
            }
            if(!empty($wh_arr)) $sql .= " and ".implode(" and ",$wh_arr);
        }
        $count_sql = $sql;
        $count_sql = str_replace('task.*',' count(*) as temp_count ',$count_sql);
        if(empty($filter) || !is_array($filter))
        {
            $sql .= " order by task.nns_create_time desc ";
        }
        $sql .= " limit $start,$size";
        $data = nl_db_get_all($sql, $dc->db());
        $rows = nl_db_get_col($count_sql, $dc->db());
        return array('data'=>$data,'rows'=>$rows);
    }

}